import { Router } from 'express'

const router = Router()

const { DataBase } = require('../utils/database/mongodb/database')
const db = new DataBase()
db.setDatabase('yndj')

// Mock Users
const test = [
  { name: 'h1' },
  { name: 'h2' },
  { name: 'h3' }
]

/* GET users listing. */
router.get('/login', function (req, res, next) {
  res.json(test)
})

// Add POST - /api/login
router.post('/login', (req, res) => {
  // 从数据库中查询
  if (!req.body.username) {
    db.findOne('users', { username: req.body.username }, doc => {
      if (!doc) {
        res.status(401).json({
          message: '用户不存在'
        })
        return
      }
      if (!doc.username) {
        res.status(401).json({
          message: '用户不存在'
        })
        return
      }
      if (req.body.username === doc.username &&
        req.body.password === doc.password) {
        req.session.authUser = doc
        return res.json(doc)
      } else {
        res.status(401).json({
          message: '密码错误'
        })
      }
    })
  }
})

router.post('/admin/login', (req, res) => {
  console.log('用户名：' + req.body.username)
  db.findOne('admin', { username: req.body.username }, dataObject => {
    console.log(dataObject)
    if (dataObject === null) {
      res.status(401).json({
        message: '用户不存在'
      })
      return
    }
    if (req.body.username === dataObject.username && req.body.password === dataObject.password) {
      console.log('登录成功')
      req.session.authUser = dataObject
      return res.json(dataObject)
    } else {
      res.status(401).json({
        message: '密码错误'
      })
    }
  })
})

// Add POST - /api/logout
router.post('/logout', (req, res) => {
  delete req.session.authUser
  res.json({ ok: true })
})

export default router
